<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="产品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 
      <el-form-item label="产品分类" prop="ptype">
        <el-input
          v-model="queryParams.ptype"
          placeholder="请输入产品分类"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      -->
      <el-form-item label="产品标签" prop="tags">
        <el-input
          v-model="queryParams.tags"
          placeholder="请输入产品标签"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!--
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
        >修改</el-button>
      </el-col>
      -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDel"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="expDatas"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="impDatas"
        >导入</el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="40" />
      <el-table-column label="品名" prop="goodsName"  width="150" />
      <el-table-column label="规格" prop="spce" width="80" />
      <el-table-column label="一级分类" prop="type1" width="80" />
      <el-table-column label="二级分类" prop="type2" width="80" />
      <el-table-column label="授权等级" prop="grantLevel" width="80" />
      <el-table-column label="配送方式" prop="deliveryMode" width="100" />
      <el-table-column label="供应商" prop="supplierName" width="200" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="170">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPerm="['role_edit']"
          >修改</el-button>
          <!--
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleDataScope(scope.row)"
            v-hasPerm="['role_data']"
          >数据权限</el-button>
          -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
            v-hasPerm="['role_del']"
          >删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handDownMainPic(scope.row)"
            v-hasPerm="['role_del']"
          >下载主图</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handDownDetailPic(scope.row)"
            v-hasPerm="['role_del']"
          >下载详图</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
  
   <el-dialog title="upload execl file" :visible.sync="uploadopen" width="400px">
   
    <el-upload
            class="upload-demo"
            :headers="upload.headers"
            :action= "uploadurl"
            accept=".xlsx, .xls"
            :on-preview="handlePreview3"
            :on-remove="handleRemove3"
            :before-remove="beforeRemove3"
            :on-success="importok"
            :on-error="importerror"
            :multiple="true"
            :limit="1"
            :on-exceed="handleExceed3"
            :file-list="fileList3">
            <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-link href="http://xingpinmao.oss-cn-beijing.aliyuncs.com/erp/1595828010753.xlsx" target="_blank">下载模板</el-link>
   </el-dialog>
    
    <el-dialog :title="title" :visible.sync="open" width="550px">
      <div>
        <el-row>
          <el-steps :active="active" finish-status="success">
            <el-step v-for="site in steps" :title="site.title"></el-step>
          </el-steps>
        </el-row>
        <el-row></el-row>

        <el-row v-show='tabopen1'>
          <el-form ref="form" :model="form" label-width="130px">            
            <el-form-item label="品名 *" prop="goodsName" class="form-item-require-lable">
              <el-input v-model="form.goodsName" placeholder="请输入品名" clearable/>
            </el-form-item>
            <el-form-item label="价格 *" prop="goodsPrice">
              <el-input v-model="form.goodsPrice" placeholder="请输入价格" clearable/>
            </el-form-item>
            <el-form-item label="提报价格 *" prop="goodsCommitPrice">
              <el-input v-model="form.goodsCommitPrice" placeholder="请输入提报价格" clearable/>
            </el-form-item>
            <el-form-item label="平台露出价 *" prop="channelPrice">
              <el-input v-model="form.channelPrice" placeholder="请输入平台露出价" clearable/>
            </el-form-item>
            <el-form-item label="产品卖点描述" prop="goodsDesc">
              <el-input v-model="form.goodsDesc" placeholder="请输入产品卖点描述" clearable/>
            </el-form-item>
            <el-form-item label="授权等级 *" prop="grantLevel">
              <el-input v-model="form.grantLevel" placeholder="请输入授权等级" clearable/>
            </el-form-item>
            <el-form-item label="配送方式 *" prop="deliveryMode">
              <el-input v-model="form.deliveryMode" placeholder="请输入配送方式" clearable/>
            </el-form-item>
            <el-form-item label="运费 *" prop="freight">
              <el-input v-model="form.freight" placeholder="请输入运费" clearable/>
            </el-form-item>
            <el-form-item label="库存 *" prop="stock">
              <el-input v-model="form.stock" placeholder="请输入库存" clearable/>
            </el-form-item>
            <el-form-item label="规格 *" prop="spce">
              <el-input v-model="form.spce" placeholder="请输入规格" clearable/>
            </el-form-item>
            <el-form-item label="产品外链" prop="goodsUrl">
              <el-input v-model="form.goodsUrl" placeholder="请输入产品外链" clearable/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" clearable/>
            </el-form-item>
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入标签" clearable/>
            </el-form-item>
            <el-form-item label="一级分类 *" prop="type1">
              <el-input v-model="form.type1" placeholder="请输入一级分类" clearable/>
            </el-form-item>
            <el-form-item label="二级分类 *" prop="type2">
              <el-input v-model="form.type2" placeholder="请输入二级分类" clearable/>
            </el-form-item>
            <el-form-item label="供应商 *" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商" clearable/>
            </el-form-item>
          </el-form>
        </el-row>

        <el-row v-show='tabopen2'>
          <el-form ref="form" :model="form" label-width="130px">
            <el-form-item label="主图" prop="fileAuth">
              <el-upload class="upload-demo"
                         :headers="upload.headers"
                         :action="upload.url"
                         :disabled="upload.isUploading"
                         :on-preview="handlePreview" 
                         :on-remove="handleRemove1" 
                         :before-remove="beforeRemove" multiple
                         :on-success="handleFileSuccess1"
                         :limit="3" :on-exceed="handleExceed" :file-list="fileAuth">
                <el-button size="small" type="primary">点击上传</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-form-item>
            <el-form-item label="详图" prop="fileTrademark">
              <el-upload
                class="upload-demo"
                :headers="upload.headers"
                :action="upload.url"
                :disabled="upload.isUploading"
                :on-preview="handlePreview" 
                :on-remove="handleRemove2" 
                :before-remove="beforeRemove" multiple :limit="20"
                :on-success="handleFileSuccess2"
                :on-exceed="handleExceed" 
                :file-list="fileTrademark">
                <el-button size="small" type="primary">点击上传</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >下一步
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct , addProduct , addProductImg , delProduct , expData , downPic , query , update , queryImg } from "@/api/prod/adm";
import {getAccessToken} from "@/utils/auth";

export default {
  name: "Prod",
  data() {
    return {
      isEdit : false,
      // 遮罩层
      loading: false,
      tabopen1:true,
      tabopen2:false,
      uploadopen:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 状态数据字典
      statusOptions: [],
      fileTrademark:[],
      // 菜单列表
      menuOptions: [],
      // 机构列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        code: undefined,
        status: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      form: {},
      steps:[{title:"基本信息"},{title:"上传图片"}],
      goodsId : undefined,
      active: 0,
      // 文件上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getAccessToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/aliyunUpload/photoUpload"
      },

      uploadurl : process.env.VUE_APP_BASE_API + "/prod/import",
      
      fileAuth: [],
      fileTrademark: [],
      imglist:[],
      fileList3:[]
    };
  },
  created() {
    this.getList();
  },
  methods: {


  handlePreview3(){},
  handleRemove3(){},
  beforeRemove3(){},
  handleExceed3(){},
  impDatas(){

    this.uploadopen = true;
  },
    getList() {
      
      this.loading = true;
      listProduct(this.queryParams).then(
        response => {
          this.roleList = response.data;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    handleSelectionChange(selection){

        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
        console.log(JSON.stringify(this.ids));
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    handleAdd(){
      this.isEdit = false;
      this.open = true;
      this.active = 0;
      this.tabopen1=true;
      this.tabopen2=false;
      this.fileAuth = [];
      this.fileTrademark = [];
      //this.resetForm("form");
      this.reset();
    },

    cancel(){
      this.open = false;
      this.active = 0;
    },
    handDownMainPic(row){
      let p = {};
      p.goodsId = row.id;
      p.type = 1;//主图
      
      window.location.href = process.env.VUE_APP_BASE_API + "/prod/downpic?goodsId="+row.id+"&type="+1;
      
    },
    handDownDetailPic(row){
      let p = {};
      p.goodsId = row.id;
      p.type = 2;//详情图
      window.location.href = process.env.VUE_APP_BASE_API + "/prod/downpic?goodsId="+row.id+"&type="+2;
  

    },
    handleDel(row){
      console.log(row);
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除ID为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delProduct(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
    },
    handleEdit(row){
      this.isEdit = true;
      this.active = 0;
      this.open = true;
      this.tabopen1=true;
      this.tabopen2=false;
      this.resetForm("form");
      if(!row.id){
          this.msgWarning("请选择要修改的记录");
          return;
      }
      //
      query(row.id).then(
        response => {
          console.log(JSON.stringify(response.data));
          this.form = response.data;
        }
      );

    },
    expDatas(){
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有产品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return expData(queryParams);
        }).then(response => {
          this.download(response.data);
        }).catch(function() {});
    },
    resetQuery(){
      this.resetForm("queryForm");
    },
    getPiclist(id){
       return queryImg(this.goodsId);
    },
    submitForm(){
      if(this.isEdit){
          if(this.active == 0){
              this.$refs["form"].validate(valid => {

                        if (!this.form.goodsName) {
                            this.msgWarning("品名不能为空");
                            return;
                        }
                        if (!this.form.goodsCommitPrice) {
                            this.msgWarning("提报价不能为空");
                            return;
                        }
                        if (!this.form.channelPrice) {
                            this.msgWarning("平台露出价不能为空");
                            return;
                        }
                        if (!this.form.grantLevel) {
                            this.msgWarning("授权等级不能为空");
                            return;
                        }
                        if (!this.form.deliveryMode) {
                            this.msgWarning("配送方式不能为空");
                            return;
                        }
                        if (!this.form.freight) {
                            this.msgWarning("运费不能为空");
                            return;
                        }
                        if (!this.form.stock) {
                            this.msgWarning("库存不能为空");
                            return;
                        }
                        if (!this.form.spce) {
                            this.msgWarning("规格不能为空");
                            return;
                        }
                        if (!this.form.type1) {
                            this.msgWarning("一级分类不能为空");
                            return;
                        }
                        if (!this.form.type2) {
                            this.msgWarning("二级分类不能为空");
                            return;
                        }
                        if (!this.form.supplierName) {
                            this.msgWarning("供应商不能为空");
                            return;
                        }

                        this.loading = true;
                        update(this.addDateRange(this.form, this.dateRange)).then(
                          response => {
                                if(response.code == 0){
                                    this.goodsId = response.data.id;
                                    this.active = 1;
                                    this.tabopen1 = false;
                                    this.tabopen2 = true;
                                    this.loading = false;
                                    
                                    //初始化图片上传框
                                    queryImg(this.goodsId).then(
                                        resp => {
                                          if(resp.code == 0){
                                              
                                              this.fileAuth = resp.data.m;
                                              this.fileTrademark = resp.data.d;

                                              //初始化IMGLIST
                                              for(let i = 0 ; this.fileAuth && i < this.fileAuth.length ; i++){
                                                  let o = {};
                                                  o.imgType =this.fileAuth[i].imgType;
                                                  o.imgName =this.fileAuth[i].name;
                                                  o.imgLongUrl=this.fileAuth[i].url;
                                                  o.imgShortUrl = this.fileAuth[i].imgShortUrl;
                                                  o.goodsId = this.fileAuth[i].goodsId;
                                                  
                                                  this.imglist.push(o);
                                              }

                                              for(let i = 0 ; this.fileTrademark && i < this.fileTrademark.length ; i++){
                                                  let o = {};
                                                  o.imgType =this.fileTrademark[i].imgType;
                                                  o.imgName =this.fileTrademark[i].name;
                                                  o.imgLongUrl=this.fileTrademark[i].url;
                                                  o.imgShortUrl = this.fileTrademark[i].imgShortUrl;
                                                  o.goodsId = this.fileTrademark[i].goodsId;
                                                  
                                                  this.imglist.push(o);
                                              }

                                          }
                                        }
                                    );
                                }else{
                                  this.loading = false;
                                  this.msgWarning(response.msg);
                                }
                          }
                        );
                    });




          }else{
              //update pic  , frist delete pic list, last add pic list
              if(this.imglist.length < 1){
                    this.msgWarning("请至少选择一张图片进行上传");
                    return;
                  }
                  addProductImg(this.imglist).then(
                      response => {
                            if(response.code == 0){
                                this.msgWarning("图片保存成功");
                                this.imglist = [];
                                this.fileAuth = [];
                                this.fileTrademark = [];
                                this.cancel();
                                this.active = 0;
                            }else{
                                this.msgWarning("图片保存失败,请重试");
                            }
                      }
                  );
          }
      }else{
          if(this.active == 0){
                this.$refs["form"].validate(valid => {

                        if (!this.form.goodsName) {
                            this.msgWarning("品名不能为空");
                            return;
                        }
                        if (!this.form.goodsCommitPrice) {
                            this.msgWarning("提报价不能为空");
                            return;
                        }
                        if (!this.form.channelPrice) {
                            this.msgWarning("平台露出价不能为空");
                            return;
                        }
                        if (!this.form.grantLevel) {
                            this.msgWarning("授权等级不能为空");
                            return;
                        }
                        if (!this.form.deliveryMode) {
                            this.msgWarning("配送方式不能为空");
                            return;
                        }
                        if (!this.form.freight) {
                            this.msgWarning("运费不能为空");
                            return;
                        }
                        if (!this.form.stock) {
                            this.msgWarning("库存不能为空");
                            return;
                        }
                        if (!this.form.spce) {
                            this.msgWarning("规格不能为空");
                            return;
                        }
                        if (!this.form.type1) {
                            this.msgWarning("一级分类不能为空");
                            return;
                        }
                        if (!this.form.type2) {
                            this.msgWarning("二级分类不能为空");
                            return;
                        }
                        if (!this.form.supplierName) {
                            this.msgWarning("供应商不能为空");
                            return;
                        }

                        this.loading = true;
                        addProduct(this.addDateRange(this.form, this.dateRange)).then(
                          response => {
                                if(response.code == 0){
                                    this.goodsId = response.data.id;
                                    this.active = 1;
                                    this.tabopen1 = false;
                                    this.tabopen2 = true;
                                    this.loading = false;
                                }else{
                                  this.loading = false;
                                  this.msgWarning(response.msg);
                                }
                          }
                        );
                    });
            }else if(this.active == 1){
                  if(this.imglist.length < 1){
                    this.msgWarning("请至少选择一张图片进行上传");
                    return;
                  }
                  addProductImg(this.imglist).then(
                      response => {
                            if(response.code == 0){
                                this.msgWarning("图片保存成功");
                                this.imglist = [];
                                this.fileAuth = [];
                                this.fileTrademark = [];
                                this.cancel();
                                this.active = 0;
                                this.getList();
                            }else{
                                this.msgWarning("图片保存失败,请重试");
                            }
                      }
                  );
            }
      }
    },
    handlePreview(f){
    },
    handleRemove1(f,flist){
      
      if(f.status == 'success'){
        for(let i = 0 ; i < this.imglist.length ; i++){
             let omg = this.imglist[i];
             if(omg.imgName == f.name && omg.imgType == 1){
                this.imglist.splice(i,1); 
             }
        }
      }
    },
    handleRemove2(f,flist){
          if(f.status == 'success'){
            for(let i = 0 ; i < this.imglist.length ; i++){
                let omg = this.imglist[i];
                if(omg.imgName == f.name && omg.imgType == 2){
                    this.imglist.splice(i,1); 
                }
            }
          }

    },
    beforeRemove(f,flist){

    },
    handleFileSuccess1(response,f,flist){
      console.log(JSON.stringify(response.data));
      let main_img_object = {};
      main_img_object.imgType =1;
      main_img_object.imgName =response.data.name;
      main_img_object.imgLongUrl=response.data.url;
      main_img_object.imgShortUrl = response.data.relativelyUrl;
      main_img_object.goodsId = this.goodsId;
      this.imglist.push(main_img_object);
    },
    handleFileSuccess2(response,f,flist){
      let main_img_object = {};
      main_img_object.imgType =2;
      main_img_object.imgName =response.data.name;
      main_img_object.imgLongUrl=response.data.url;
      main_img_object.imgShortUrl = response.data.relativelyUrl;
      main_img_object.goodsId = this.goodsId;
      this.imglist.push(main_img_object);
    },
    handleExceed(fs,flist){

    },
    importok(response,f,flist){

      if(response.code == 0){
        this.msgWarning("导入成功");
        this.uploadopen=false;
        this.fileList3=[];
        this.getList();
      }else{
        this.msgWarning("导入失败:" + response.msg);
      }
    },
    importerror(err,f,flist){
      //console.log(JSON.stringify(err));
      //console.log(JSON.stringify(f));
      //console.log(JSON.stringify(flist));
      this.msgWarning("导入失败" );

    }
  }
};
</script>
